package com.example.handemp.demos.web;

import com.example.feign.DepFeignService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


@RestController
@Slf4j
@Api(tags = "测试接口")
@ResponseBody
public class BasicController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DepFeignService depFeignService;
    @Autowired
    private User user;

    @GetMapping("/hello")
    @ResponseBody
    public String hello(@RequestParam(name = "name", defaultValue = "unknown user") String name) {
        return "Hello " + name;
    }

    @GetMapping("/testProperties")
    @HystrixCommand(fallbackMethod = "getHelloFallback")
    @ApiOperation(value = "读取自定义配置测试接口")
    public String testProperties() {
        log.info("通过@ConfigurationProperties读取yaml配置文件中的自定义配置{}， {}",
                user.getNames(), user.getAge());
        return user.getNames();
    }

    @GetMapping("/testFeign")
    @ApiOperation(value = "测试Feign的接口")
    public Object testFeign(Integer id){
        log.info("测试Feign的正常使用");
        return depFeignService.load(id);
    }

    @GetMapping("/testHystrix")
    @HystrixCommand(fallbackMethod = "getHelloFallback")
    @ApiOperation(value = "Hystrix熔断测试接口")
    public String getHello() {
        log.info("[getUser][准备调用另一个 HandEmp]");
        return restTemplate.getForEntity("http://127.0.0.1:8801/user1", String.class).getBody();
    }

    public String getHelloFallback(Throwable throwable) {
        log.error("[getHelloFallback][exception({})]", ExceptionUtils.getRootCauseMessage(throwable));
        return "mock:Hello";
    }

}
